import { net } from 'electron'

export class NetworkService {
    private static currentOnline = true

    static setOnline(value: boolean) {
        NetworkService.currentOnline = !!value
    }

    static getOnline(): boolean {
        return NetworkService.currentOnline
    }

    static isOnline(timeoutMs = 2000): Promise<boolean> {
        return new Promise((resolve) => {
            try {
                const request = net.request({ method: 'GET', url: 'https://www.gstatic.com/generate_204' })
                const timer = setTimeout(() => {
                    try { request.abort() } catch { }
                    resolve(false)
                }, timeoutMs)
                request.on('response', (res) => {
                    clearTimeout(timer)
                    resolve((res.statusCode || 0) >= 200 && (res.statusCode || 0) < 400)
                })
                request.on('error', () => {
                    clearTimeout(timer)
                    resolve(false)
                })
                request.end()
            } catch {
                resolve(false)
            }
        })
    }
}

export default NetworkService


